package la.bbs558.aop.delay.handler;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import la.bbs558.entity.BbsClass;
import la.bbs558.entity.BbsClassActive;
import la.bbs558.service.BbsClassActiveService;
import la.bbs558.service.BbsClassService;
import la.bbs558.util.ExecutorManager;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: Shanks
 * @date: 2024/1/19 14:26
 * @desc:
 */
@Component
public class BbsClassActiveInitDelay implements InitializingBean {

    @Resource
    private BbsClassActiveService bbsClassActiveService;
    @Resource
    private BbsClassService bbsClassService;
    @Override
    public void afterPropertiesSet() {
        ExecutorManager.delayExecutor.execute(()->{
            DateTime now = DateUtil.date();
            List<BbsClassActive> classActives = bbsClassActiveService.lambdaQuery()
                    .ge(BbsClassActive::getStartTime,now)
                    .or()
                    .ge(BbsClassActive::getEndTime,now)
                    .list();
            //判断是否有需要处理的主题活动
            if(classActives.isEmpty()){
                return;
            }
            List<Long> activityIds = classActives.stream().map(BbsClassActive::getId).collect(Collectors.toList());
            List<BbsClass> bbsClasses = bbsClassService.lambdaQuery()
                    .in(BbsClass::getActivityId,activityIds)
                    .list();
            //判断是否有需要处理的主题
            if(bbsClasses.isEmpty()){
                return;
            }
            for (BbsClass bbsClass : bbsClasses) {
                //创建延时任务
                bbsClassActiveService.addTask(bbsClass);
            }
        });
    }
}
